loops
Loops: while and for #
Author: @Fatmasiam#
As we learned previously in the loop session
Loops are handy, if you want to run the same code over and over again, each time with a different value. We often need to repeat actions. For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10. Loops are a way to repeat the same code multiple times.
NOW How loops work with arrays:#
The “while” loop:#
A single execution of the loop body is called an iteration. The loop in the example above makes three iterations.
If i++ was missing from the example above, the loop would repeat (in theory) forever.
In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.
The following example uses the while loop statement to add 5 random numbers between 0 and 10 to an array:
In this example: ⏫
- First, declare and initialize an array.
- Second, add a random number between 0 and 10 in each loop iteration inside the
whilestatement. If the value of thecountequals the value of thesizevariable, the loop stops.
The “do…while” loop#
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.
For example:
Refreshing Question *️⃣ ==> separate[explain] the work for the previous example if the condition will i <= alpha.length
The “for” loop#
The for loop is more complex, but it’s also the most commonly used loop.
Here’s exactly what happens in our case:
Summary#
We covered 3 types of loops:#
while– The condition is checked before each iteration.do..while– The condition is checked after each iteration.for (;;)– The condition is checked before each iteration, additional settings available.- To make an “infinite” loop, usually the
while(true)construct is used. Such a loop, just like any other, can be stopped with thebreakdirective.
If we don’t want to do anything in the current iteration and would like to forward to the next one, we can use the continue directive.